<?php
namespace app\controllers;

use app\models\eventType;
use app\models\Plan;
use yii\web\Controller;
use app\common\BaseController;

class PlanController extends BaseController{
    public function actionIndex(){
        $allTypes = eventType::find()->asArray()->all();
        $startTime = date('Y-m-d 00:00:00');
        $endTime = date('Y-m-d 23:59:59');
        $curPlan = Plan::find()->where(['>=', 'planTime', $startTime])->andWhere(['<', 'planTime', $endTime])->asArray()->all();

        return $this->result([
            'type' => $allTypes,
            'plan' => $curPlan
        ]);
    }

    public function actionGetPlanList () {
        $searchTime = \Yii::$app->request->post('searchTime');
        $startTime = $searchTime . ' 00:00:00';
        $endTime = $searchTime . ' 23:59:59';
        $planList = Plan::find()->where(['>=', 'planTime', $startTime])->andWhere(['<', 'planTime', $endTime])->asArray()->all();
        return $this->result($planList);
    }

    public function actionSetPlan(){
        $postData = \Yii::$app->request->post();
        $planTime = $this->getTime($postData['curTime'], $postData['planId']);
        $planObj = Plan::find()->where(['planTime' => $planTime])->one();
        if (!$planObj){
            $planObj = new Plan();
            $planObj->planTime = $planTime;
            $planObj->index = $postData['planId'];
        }
        $planObj->eventId = $postData['eventId'];
        $planObj->ctime = time();
        $res = 1;
        if ($planObj->save()){
            $res = 0;
        }
        return $this->result([], $res, $planObj->errors);
    }

    public function actionSetPlanThing() {
        $postData = \Yii::$app->request->post();
        $planTime = $this->getTime($postData['curTime'], $postData['planId']);
        $planObj = Plan::find()->where(['planTime' => $planTime])->one();
        if (!$planObj){
            $planObj = new Plan();
            $planObj->planTime = $planTime;
            $planObj->index = $postData['planId'];
        }
        $planObj->thing = $postData['thing'];
        $planObj->ctime = time();
        $res = 1;
        if ($planObj->save()){
            $res = 0;
        }
        return $this->result([], $res);
    }

    public function getTime($curTime, $index){
        $cDate = date('Y-m-d', $curTime);
        $hour = floor($index / 2);
        if ($index % 2){
            $hour .= ':30:00';
        }else{
            $hour .= ':00:00';
        }
        return $cDate . ' ' .$hour;
    }
}